/***引入axios***/
import axios from 'axios';
import { Message } from 'element-ui';
//加密
import CryptoJS from 'crypto-js';

let pathUrl = process.env.NODE_ENV === 'production'? location.origin :"/api";

const key = CryptoJS.enc.Utf8.parse("`longwill2021=)(");  //十六位十六进制数作为密钥

let loginUrl = location.origin + location.pathname + '#/login';

let base = {
  /***get请求***/
  getAjax(url, dataObj) {
    let Authorization = JSON.parse(sessionStorage.getItem('loginInfo')) ? JSON.parse(sessionStorage.getItem('loginInfo')).token : "";
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url: pathUrl + url,
        headers: { 'Authorization': Authorization },
        params: dataObj,
        timeout: 60000,
      }).then(res => {
        if (res.status == 200) {
          if (res.data.code == 200) {
            resolve(res);
          } else if (res.data.code == 401) {
            //登录失效
            Message.error(res.data.msg)
            sessionStorage.clear();
            location.href = loginUrl;
          } else {
            Message.error(res.data.msg)
            return;
          }
        } else {
          Message.error(res.statusText)
          return;
        }
      }).catch(function (error) {
        if (error.response) {
          Message.error("系统故障，请联系管理员")
          return;
        } else if (error.request) {
          Message.error("请求超时，请重新登录")
          return;
        } else {
          Message.error(error.msg)
          return;
        }
      });
    })
  },
  /***获取验证码***/
  getImgCode(url, dataObj) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url: pathUrl + url,
        params: dataObj,
        timeout: 60000,
        responseType: "arraybuffer"
      }).then(res => {
        if (res.status == 200) {
          resolve(res);
        } else if (res.data.code == 401) {
          Message.error(res.data.msg)
          sessionStorage.clear();
          location.href = loginUrl;
        } else {
          Message.error(res.statusText)
          return;
        }
      }).catch(function (error) {
        if (error.response) {
          Message.error("系统故障，请联系管理员")
          return;
        } else if (error.request) {
          Message.error("请求超时，请重新登录")
          return;
        } else {
          Message.error(error.msg)
          return;
        }
      });
    })
  },
  /***post请求,json形式***/
  postAjax(url, data, newValue, isHide) {
    let headers = {};
    let Authorization = JSON.parse(sessionStorage.getItem('loginInfo')) ? JSON.parse(sessionStorage.getItem('loginInfo')).token : "";

    let onlineUrl = pathUrl + url + '?Authorization=' + Authorization;
    if (newValue) {
      onlineUrl = pathUrl + url + '?Authorization=' + Authorization + newValue;
    };
    if (isHide) {
      onlineUrl = pathUrl + url
    } else {
      headers = { 'Authorization': Authorization };
    }

    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: onlineUrl,
        headers: headers,
        data: data,
        timeout: 60000,
      }).then(res => {
        if (res.status == 200) {
          if (res.data.code == 200) {
            resolve(res);
          } else if (res.data.code == 401) {
            Message.error(res.data.msg)
            sessionStorage.clear();
            location.href = loginUrl;
          } else {
            Message.error(res.data.msg)
            if (url == '/security/login') {
              resolve(res);
            }
            return;
          }
        } else {
          Message.error(res.statusText)
          return;
        }
      }).catch(function (error) {
        if (error.response) {
          Message.error("系统故障，请联系管理员")
          return;
        } else if (error.request) {
          Message.error("请求超时，请重新登录")
          return;
        } else {
          Message.error(error.msg)
          return;
        }
      });
    })

  },
  /***post请求，form-data形式***/
  postForm(url, data) {
    let Authorization = JSON.parse(sessionStorage.getItem('loginInfo')) ? JSON.parse(sessionStorage.getItem('loginInfo')).token : "";

    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: pathUrl + url + '?Authorization=' + Authorization,
        headers: { 'Authorization': Authorization },
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        data: data,
        timeout: 60000,
      }).then(res => {
        if (res.status == 200) {
          if (res.data.code == 200) {
            resolve(res);
          } else if (res.data.code == 401) {
            Message.error(res.data.msg)
            sessionStorage.clear();
            location.href = loginUrl;
          } else {
            Message.error(res.data.msg)
            return;
          }
        } else {
          Message.error(res.statusText);
          return;

        }
      }).catch(function (error) {
        if (error.response) {
          Message.error("系统故障，请联系管理员")
          return;
        } else if (error.request) {
          Message.error("请求超时，请重新登录")
          return;
        } else {
          Message.error(error.msg)
          return;
        }
      });
    })
  },
  /***post并发请求***/
  postAll(funArray) {
    let itemArray = [], reqUrl = [], item;
    for (let index = 0; index < funArray.length; index++) {
      itemArray.push('value' + index);
      console.log(funArray[index]);
      reqUrl.push(this.postForm('6', funArray[index]))
    };
    return;
    item = itemArray.join(',');
    //[getUserAccount(), getUserPermissions()]
    return new Promise((resolve, reject) => {
      axios.all(reqUrl)
        .then(axios.spread((item) => {
          // 两个请求现在都执行完成
          console.log(item);
          resolve(item);
        }));
    })
  },
  /***delete请求 */
  deleteAjax(url, data) {
    let Authorization = JSON.parse(sessionStorage.getItem('loginInfo')) ? JSON.parse(sessionStorage.getItem('loginInfo')).token : "";

    return new Promise((resolve, reject) => {
      axios({
        method: 'delete',
        url: pathUrl + url + '?Authorization=' + Authorization,
        headers: { 'Authorization': Authorization },
        data: data,
        timeout: 60000,
      }).then(res => {
        if (res.status == 200) {
          if (res.data.code == 200) {
            resolve(res);
          } else if (res.data.code == 401) {
            Message.error(res.data.msg)
            sessionStorage.clear();
            location.href = loginUrl;
          } else {
            Message.error(res.data.msg)
            return;
          }
        } else {
          Message.error(res.statusText);
          return;
        }
      }).catch(function (error) {
        if (error.response) {
          Message.error("系统故障，请联系管理员")
          return;
        } else if (error.request) {
          Message.error("请求超时，请重新登录")
          return;
        } else {
          Message.error(error.msg)
          return;
        }
      });
    })
  },
  deleteRequest( url) {
    let Authorization = JSON.parse(sessionStorage.getItem('loginInfo')) ? JSON.parse(sessionStorage.getItem('loginInfo')).token : "";

    return new Promise((resolve, reject) => {
      axios({
        method: 'delete',
        url: pathUrl + url + '&Authorization=' + Authorization,
        headers: { 'Authorization': Authorization },
        timeout: 60000,
      }).then(res => {
        if (res.status == 200) {
          if (res.data.code == 200) {
            resolve(res);
          } else if (res.data.code == 401) {
            Message.error(res.data.msg)
            sessionStorage.clear();
            location.href = loginUrl;
          } else {
            Message.error(res.data.msg)
            return;
          }
        } else {
          Message.error(res.statusText);
          return;
        }
      }).catch(function (error) {
        if (error.response) {
          Message.error("系统故障，请联系管理员")
          return;
        } else if (error.request) {
          Message.error("请求超时，请重新登录")
          return;
        } else {
          Message.error(error.msg)
          return;
        }
      });
    })
  },
  /***axios通用***/
  axiosPost(onlineUrl, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: onlineUrl,
        data: data,
        timeout: 60000,
      }).then(res => {
        if (res.status == 200) {
          resolve(res);
        } else {
          Message.error('请求出错')
          return;
        }
      }).catch(function (error) {
        if (error.response) {
          Message.error("系统故障，请联系管理员")
          return;
        } else if (error.request) {
          Message.error("请求超时，请重新登录")
          return;
        } else {
          Message.error(error.msg)
          return;
        }
      });
    })
  },

  /**java使用sha1prng算法**/
  /***AES加密***/
  encryptAES(word) {
    var sContent = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(sContent, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.toString();
  },
  //解密
  decryptAES(word) {
    var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
  },
  /*获取uuid*/
  guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  },
  /***数字验证***/
  isNumberVerify(val) {
    var myReg = /^[0-9]+(\.\d+)?$/;
    if (!myReg.test(val)) {
      return false;
    } else {
      return true;
    }
  },
  /***姓名验证***/
  isNameVerify(name) {
    var myReg = /^(?:[\u4e00-\u9fa5]+)(?:●[\u4e00-\u9fa5]+)*$|^[a-zA-Z0-9]+\s?[\.·\-()a-zA-Z]*[a-zA-Z]+$/;
    if (!myReg.test(name)) {
      return false;
    } else {
      return true;
    }
  },

  /***手机号验证***/
  isPoneAvailable(val) {
    //var myreg = /^1([389][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
    var myreg = /^\d{11}$/;
    if (myreg.test(val)) {
      return true;
    } else {
      return false;
    }
  },
  /**身份证 */
  isCardVerify(card) {
    var myReg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
    if (!myReg.test(card)) {
      return false;
    } else {
      return true;
    }
  },
  /***时间转换***/
  timeSwitch(val, judge) {
    let date = new Date(val);
    let Month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let second = date.getSeconds();
    if (judge) {
      return date.getFullYear() + '-' + this.isTwo(Month) + '-' + this.isTwo(day) + ' ' + this.isTwo(hours) + ':' + this.isTwo(minutes) + ':' + this.isTwo(second);
    } else {
      return date.getFullYear() + '-' + this.isTwo(Month) + '-' + this.isTwo(day)
    }
  },
  isTwo(val) {
    if (val.toString().length > 1) {
      return val;
    } else {
      return '0' + val;
    }
  },
  //只显示月份
  showMonth(val) {
    let date = new Date(val);
    let Month = date.getMonth() + 1;
    return date.getFullYear() + '-' + this.isTwo(Month)
  },
  //根据出生日期计算年龄
  sumAge(value) {
    let currentYear = new Date().getFullYear();
    let currentMon = new Date().getMonth() + 1;
    let currentDate = new Date().getDate();
    let birthYear = new Date(value).getFullYear();
    let birthMon = new Date(value).getMonth() + 1;
    let birthDate = new Date(value).getDate();
    let differ = currentYear - birthYear;
    if (birthMon > currentMon) {
      differ--;
    } else if (birthMon == currentMon) {
      if (birthDate > currentDate) {
        differ--;
      }
    }
    return differ;
  },
  //根据身份证号查年龄
  sumAgeByIdCard(idCard) {
    var date = new Date();
    if (idCard) {
      var currentYear = date.getFullYear();
      var currentMon = date.getMonth() + 1;
      var currentDate = date.getDate();
      var birthYear = idCard.substring(6, 10);
      var birthMon = idCard.substring(10, 12);
      var birthDate = idCard.substring(12, 14);
      var differ = currentYear - birthYear;
      if (birthMon > currentMon) {
        differ--;
      } else if (birthMon == currentMon) {
        if (birthDate > currentDate) {
          differ--;
        }
      }
      return differ;
    } else {
      return 0;
    }
  },
  /***隐私化姓名***/
  privacyName(e) {
    if (e) {
      var length = e.length - 1;
      var start = e.substring(0, 1);
      for (var i = 0; i < length; i++) {
        start = start + "*";
      }
      return start
    } else {
      return e;
    }
  },
  /***隐私化手机号***/
  privacyPhone(e) {
    if (e) {
      var start = e.substring(0, 3);
      var end = e.substring(7, 11);
      return start + "****" + end;
    } else {
      return e;
    }
  },
  /***隐私化身份证***/
  privacyIdCard(e) {
    if (e) {
      var start = e.substring(0, 6);
      var end = e.substring(14, 18);
      return start + "********" + end;
    }
  },
  genderFormatter(e) {
    if (e == 1) {
      return '男';
    } else {
      return '女';
    }
  },
  //乘法 
  accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
  },
  //加法
  accAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
  },
  //除法
  accDiv(arg1, arg2) {
    var t1 = 0,
      t2 = 0,
      r1, r2;
    try {
      t1 = arg1.toString().split(".")[1].length
    } catch (e) { }
    try {
      t2 = arg2.toString().split(".")[1].length
    } catch (e) { }
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
  },
  //减法
  accSubtr(arg1, arg2) {
    var r1, r2, m, n;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
  },
}
export default base;